module.exports = class extends think.Logic {
  async getUserList(uid = '') {
    let list;
    if (think.isEmpty(uid)) {
      list = await think.model('user').where({}).field('username,mobile,email').select();
    } else {
      list = await think.model('user').where({id: ['!=', uid]}).field('username,mobile,email').select();
    }

    const userInfo = {username: [], mobile: [], email: []};
    list.forEach((item) => {
      userInfo.username.push(item.username);
      if (!think.isEmpty(item.mobile)) {
        userInfo.mobile.push(item.mobile);
      }
      if (!think.isEmpty(item.email)) {
        userInfo.email.push(item.email.toLowerCase());
      }
    });

    return userInfo;
  }

  async putAction() {
    // 排除用户自身的id
    const userInfo = await this.getUserList(this.get('id'));

    const rules = {
      username: {
        // notIn: ['admin', 'root', 'system', 'sys', 'user', 'manager', 'teacher', 'student', 'school', 'guest', 'site'],
        notIn: userInfo.username,
        string: true,
        required: true,
        length: {min: 3, max: 30}
      },
      email: {
        notIn: userInfo.email,
        string: true,
        required: true
      },
      mobile: {
        notIn: userInfo.mobile,
        string: true,
        required: true
      }
      // password: {
      //   string: true,
      //   required: true,
      //   length: {min: 6, max: 30}
      // },
    };
    const msgs = {
      username: '必须设置登陆用户名，最少3个字母',
      mobile: '必须设置手机号码，并且不能被注册过',
      email: '必须设置电子邮箱地址，并且不能被注册过'
      // password: '必须设置登陆密码，最少6位字母或者数字组成'
    };
    const flag = this.validate(rules, msgs);
    if (!flag) {
      return this.fail(1001, 'validate error', this.validateErrors);
    }
  }

  async postAction() {
    if (this.post('tag')) {
      return;
    }

    const userInfo = await this.getUserList();
    const rules = {
      username: {
        // notIn: ['admin', 'root', 'system', 'sys', 'user', 'manager', 'teacher', 'student', 'school', 'guest', 'site'],
        notIn: userInfo.username,
        string: true,
        required: true,
        length: {min: 3, max: 30}
      },
      email: {
        notIn: userInfo.email,
        string: true,
        required: true
      },
      mobile: {
        notIn: userInfo.mobile,
        string: true,
        required: true
      },
      password: {
        string: true,
        required: true,
        length: {min: 6, max: 30}
      }
    };
    const msgs = {
      username: '必须设置登陆用户名，最少3个字母',
      mobile: '必须设置手机号码，并且不能被注册过',
      email: '必须设置电子邮箱地址，并且不能被注册过',
      password: '必须设置登陆密码，最少6位字母或者数字组成'
    };
    const flag = this.validate(rules, msgs);
    if (!flag) {
      return this.fail(1001, 'validate error', this.validateErrors);
    }
  }
};
